package com.lu.common.utils;

import com.lu.common.domain.DbUrl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

public class DBTools {
	
	private static Connection connection;
	private static Statement statement;
	private static PreparedStatement preparedStatement;
	private static ResultSet resultSet;
	private static String dbDriver;
	private static String dbUrl;
	private static String dbUser;
	private static String dbPassword;
	private int count;

	public DBTools(DbUrl db){
		dbDriver=db.getDriver();
		dbUrl=db.getUrl();
		dbUser=db.getUsername();
		dbPassword=db.getPassword();
	}

	public Connection getCon() {
		try {
			Class.forName(dbDriver);
			connection = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
			System.out.println("getCon");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return null;
		}
		return connection;
	}
	
	public Statement getSta(){
		try {
			connection=getCon();
			statement=connection.createStatement();
			System.out.println("getSta");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return null;
		}
		return statement;
	}
	
	public PreparedStatement getPreSta(String sql){
		try {
			connection=getCon();
			preparedStatement=connection.prepareStatement(sql);
			System.out.println("pre");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return null;
		}
		return preparedStatement;
	}
	
	public ResultSet getQuery(String sql){
		try {
			statement=getSta();
			resultSet=statement.executeQuery(sql);
			System.out.println("res");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return null;
		}
		return resultSet;
	}
	
	public int nextId(String table){
		String sql="select max(id) from "+table+"";
		ResultSet rs=getQuery(sql);
		try {
			while(rs.next()){
				count=rs.getInt(1);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return count+1;
	}
	
	public int update(String sql){
		try {
			if(statement==null||statement.isClosed()){
				statement=getSta();
			}
			count=statement.executeUpdate(sql);
			System.out.println("update");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return count;
	}
	
	public void commit(){
		try {
			connection.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void close(){
		try {
			if(resultSet!=null&&!resultSet.isClosed()){
				resultSet.close();
			}
			if(statement!=null&&!statement.isClosed()){
				statement.close();
			}
			if(connection!=null&&!connection.isClosed()){
				connection.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
